package com.omall.open.sdk.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * httpResponse的解析
 */
public final class CommonUtil {

    /**
     * 解析http请求的response
     *
     * @param method
     * @return 请求结果
     * @throws IOException
     */
    public static String parserResponse(HttpMethodBase method) throws IOException {
        StringBuffer contentBuffer = new StringBuffer();
        InputStream in = method.getResponseBodyAsStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, method.getResponseCharSet()));
        String inputLine = null;
        while ((inputLine = reader.readLine()) != null) {
            contentBuffer.append(inputLine);
            contentBuffer.append("/n");
        }
        //去掉结尾的换行符
        contentBuffer.delete(contentBuffer.length() - 2, contentBuffer.length());
        in.close();
        return contentBuffer.toString();
    }

    /**
     * 仅将请求参数作为签名因子进行签名
     *
     * @param params api请求的各参数键值对
     * @param secret
     * @return
     */
    public static String signatureWithParamsOnly(Map<String, Object> params, String secret) {
        LinkedList<String> paramValueList = new LinkedList<String>();
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                Object value = entry.getValue();
                paramValueList.add(entry.getKey() + (value instanceof String ? value : JSONObject.toJSONString(value)));
            }
        }
        Collections.sort(paramValueList);
        paramValueList.addFirst(secret);
        paramValueList.addLast(secret);

        String dataStr = StringUtils.join(paramValueList, "");
        return SecurityUtil.getMD5Str(dataStr);
    }


    /**
     * 将日期转为yyyy-MM-dd HH:mm:ss格式
     *
     * @param date
     * @return
     */
    public static String format(Date date) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return fmt.format(date);
    }

    /**
     * 将日期转为yyyy-MM-dd HH:mm:ss格式
     *
     * @param date
     * @return
     */
    public static Date parse(String date) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return fmt.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 取一年后的日期
     *
     * @return
     */
    public static Date getNextYear() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.YEAR, 1);
        Date date = calendar.getTime();
        return date;
    }

    /**
     * 获取完整的url
     *
     * @param url    请求uri
     * @param params 请求参数
     * @return
     */
    public static String getWholeUrl(String url, Map<String, Object> params) {
        if (url == null) {
            return null;
        }
        if (params == null) {
            return url;
        }
        Set<Map.Entry<String, Object>> set = params.entrySet();
        if (set.size() <= 0) {
            return url;
        }
        StringBuilder __param = new StringBuilder();

        Iterator<Map.Entry<String, Object>> it = set.iterator();
        if (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            __param.append(entry.getKey()).append("=").append(encodeUtf8(String.valueOf(entry.getValue())));
        }
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            __param.append("&").append(entry.getKey()).append("=").append(encodeUtf8(String.valueOf(entry.getValue())));
        }

        return new StringBuilder(url).append("?").append(__param.toString()).toString();
    }

    public static String encodeUtf8(String val) {
        if (StringUtils.isEmpty(val)) {
            return val;
        }
        try {
            return URLEncoder.encode(val, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return val;
        }
    }

}
